package com.atguigu.gulimall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;

//配置跨域请求
@Configuration
public class GulimallCorsConfiguration {

    private static final String ALL = "*";
    private static final Long MAX_AGE = 18000L;

    @Bean
    public CorsWebFilter corsWebFilter(){

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        //配置跨域
        // #允许访问的头信息,*表示全部
        corsConfiguration.addAllowedHeader(ALL);
        // 允许提交请求的方法类型，*表示全部允许
        corsConfiguration.addAllowedMethod(ALL);
        // #允许向该服务器提交请求的URI，*表示全部允许，在SpringMVC中，如果设成*，会自动转成当前请求头中的Origin
        corsConfiguration.addAllowedOrigin(ALL);
        //允许带cookie跨域
        corsConfiguration.setAllowCredentials(true);
        // 预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
//        corsConfiguration.setMaxAge(MAX_AGE);
//        //配置前端js允许访问的自定义响应头
//        corsConfiguration.addExposedHeader(ALL);

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}
